import React, { useState, useEffect } from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi'

type Props = {
    url: string,
    goods: any,
    dispatch: any,
    type: string,
    index: number,
    action: string,
    isEditUrl: any,
    prop: string,
    skins: boolean,
    skills: boolean
}

function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

function UpLoad({ url, goods, dispatch, type, index, action, isEditUrl, prop, skins, skills }: Props) {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")

    // 判断是编辑还是新增
    useEffect(() => {
        if (isEditUrl) {
            setImageUrl(isEditUrl)
        }
    }, [])

    function handleChange(info: any) {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            dispatch({ type, prop: prop? prop: "icon", val: info.file.response.url, index, action, skins, skills })
            getBase64(info.file.originFileObj, (imageUrl: any) => {
                setLoading(false)
                setImageUrl(imageUrl)
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div>
            <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={url}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </div>
    )
}

const mapStateToProps = (state: any) => {
    const { goods } = state
    return {
        goods
    }
}

export default connect(mapStateToProps)(UpLoad)